/*
 * @Author: liu
 * @Date: 2024-04-21 13:02:29
 * @LastEditors: liu
 * @LastEditTime: 2024-05-04 11:38:41
 * @FilePath: \yyx_ser_ts\app\controller\CourseController.ts
 * @Description:课程相关控制器
 * 天道酬勤
 */
import { Context } from 'koa'
import response from '../../utils/response'
import {
  ChapterException,
  GetCourseException,
  UpdateChapterException,
  UpdateLessonException
} from '../exception/HttpException'
import CourseService from '../service/CourseService'
import {
  get,
  post,
  del,
  controller,
  use,
  unifyUse
} from '../router/decorator/index'
import commonMiddleware from '../middleware/common'
import { chapterResInfo, CourseInfo, LessonResInfo } from '../types/custom'
import { authToken } from '../middleware/AuthMiddleware'

/** 装饰器router class */
export type RouterController<T extends string> = {
  [key in T]: (ctx: Context) => Promise<void>
}

type MethodName = 'getName' | 'postName' | 'deleteName'

@controller('/course')
class CourseController {
  //新增课程接口
  @post('/saveCourseInfo')
  async saveCourseInfo(ctx: Context) {
    let courseInfo: CourseInfo = ctx.request.body
    try {
      const res = await CourseService.saveCourseInfoSer(courseInfo)
      response.success(ctx, res, '课程新增成功！')
    } catch (error: any) {
      throw new GetCourseException(error, error.msg)
      //console.log(err.sqlMessage)
      // saveCourseInfoError.result = err
      // return ctx.app.emit('error', saveCourseInfoError, ctx)
    }
  }

  //通过ID获取单门课程信息
  @get('/getCourseInfoById')
  async getCourseInfoById(ctx: Context) {
    try {
      const { id } = ctx.request.query
      //把字符串类型转换为数字类型
      let courseId = Number(id)
      const res = await CourseService.findCourseInfoById(courseId)
      response.success(ctx, res, '通过ID获取课程信息成功！')
    } catch (error: any) {
      throw new GetCourseException(error, error.messages)
    }
  }

  //获取课程列表接口
  @get('/getCourseList')
  @use(authToken)
  async getCourseList(ctx: Context) {
    try {
      //1.解析pageNum和pageSize
      const { pageNum = 1, pageSize = 10 } = ctx.request.query

      let pagenum = Number(pageNum)
      let pagesize = Number(pageSize)

      //2.调用数据处理的方法
      const res = await CourseService.findAllCourses(pagenum, pagesize)

      //3.返回结果
      response.success(ctx, res, '获取课程列表成功！')
    } catch (error: any) {
      response.failResponse(ctx, error.msg)
    }
  }

  //通过ID删除单个课程
  @del('/course')
  async deleteCourseById(ctx: Context) {
    const _id = ctx.request.query.id

    const id = Number(_id)
    // console.log(id)
    try {
      const res: any = await CourseService.findCourseInfoById(id)
      // console.log(res.dataValues)
    } catch (err) {
      response.failResponse(ctx, '课时不存在,无法删除！')
      return
    }
    //console.log('11')
    const row: any = await CourseService.deleteCourse(id)
    if (row > 0) {
      response.success(ctx, { count: row }, '课时删除成功！')
    } else {
      response.failResponse(ctx, '课时删除失败!')
    }
  }

  //通过多个ID批量删除课程
  @del('/courses')
  async deleteCoursesByIds(ctx: Context) {
    const { list } = ctx.request.body
    //  console.log(list)
    //  const list = ctx.request.query.list
    //   console.log(typeof list)

    if (!Array.isArray(list)) {
      response.failResponse(ctx, '参数不为数组!')
    }

    if (list.length === 0) {
      response.failResponse(ctx, '参数不能为空数组!')
    }
    // if (!isArrayString(list)) {
    //   // 如果解析失败，说明不是有效的数组字符串
    //   //throw new ParameterException([], '参数不为数组!')
    //   response.error(ctx, '参数不为数组!')
    // }

    // let listData = JSON.parse(list as string)

    // if (isEmptyArr(listData)) {
    //   //  throw new ParameterException([], '参数为空数组!')
    //   response.error(ctx, '参数不能为空数组!')
    // }

    let row = 0
    try {
      row = await CourseService.deleteCourses(list)
      // console.log(row, 'res')
    } catch (err) {
      return false
    }

    if (row > 0) {
      response.success(ctx, { count: row }, `批量删除课程成功，删除数${row}！`)
    } else {
      response.failResponse(ctx, '批量删除课程失败!')
    }
  }

  //获取所有章节信息
  @get('/getAllChapter')
  async getAllChapter(ctx: Context) {
    try {
      const res = await CourseService.findAllChapter()
      //  console.log(res)

      response.success(ctx, res, '获取章节信息成功！')
    } catch (error: any) {
      throw new ChapterException(error, '获取章节信息异常', 50000)
    }
  }

  //通过ID获取章节信息
  @get('/getChapterById')
  async getChapterById(ctx: Context) {
    try {
      const { id } = ctx.request.query
      console.log(id)
      //把字符串类型转换为数字类型
      let courseId = Number(id)
      if (!id) {
        throw 'id不存在！'
      }

      const res = await CourseService.findChapterById(courseId)
      ctx.body = {
        code: 0,
        message: '通过ID获取章节信息成功!',
        data: res
      }
    } catch (error: any) {
      throw new ChapterException(error, error.msg)
    }
  }

  //通过课程ID查找所有章节和课时信息
  @get('/getChAndLeByCourseId')
  async getChAndLeByCourseId(ctx: Context) {
    // console.log(ctx.request.query)
    try {
      const { courseId } = ctx.request.query
      if (!courseId) {
        throw 'courseId 不存在！'
      }
      // console.log(courseId)
      //把字符串类型转换为数字类型

      let courseId1 = Number(courseId)

      const res = await CourseService.findChAndLeByCourseId(courseId1)
      response.success(ctx, res, '通过课程ID查找所有章节和课时信息成功！')
    } catch (error: any) {
      throw new ChapterException(error, error.msg)
    }
  }

  //通过章节ID查找所有章节和课时信息
  @get('/getChAndLeByChapterId')
  async getChAndLeByChapterId(ctx: Context) {
    // console.log(ctx.request.query)
    try {
      const { chapterId } = ctx.request.query
      if (!chapterId) {
        throw 'chapterId 不存在！'
      }
      // console.log(chapterId)
      //把字符串类型转换为数字类型

      let courseId1 = Number(chapterId)

      const res = await CourseService.findChAndLeByCourseId(courseId1)
      response.success(ctx, res, '通过课程ID查找所有章节和课时信息成功！')
    } catch (error: any) {
      throw new ChapterException(error, error.msg)
    }
  }

  //新增或保存章节信息
  @post('/saveOrUpdateChapter')
  async saveOrUpdateChapter(ctx: Context) {
    let chapterInfo = ctx.request.body
    // console.log(chapterInfo)

    try {
      const res: chapterResInfo | boolean = await CourseService.updateChapter(
        chapterInfo
      )
      console.log(res)
      if ((res as chapterResInfo).id) {
        response.success(ctx, res, '章节新增成功!')
      } else if (res === true) {
        let data = {
          data: true
        }
        response.success(ctx, data, '章节更新成功！')
      } else {
        throw new UpdateChapterException('', '章节更新失败')
      }
    } catch (error: any) {
      throw new UpdateChapterException(error, error.msg)
    }
  }

  @post('/updateChapterStatus')
  async updateChapterStatus(ctx: Context) {
    try {
      const id: number = ctx.request.body.id
      console.log(id)

      const status: number = ctx.request.body.status
      console.log(status)
      const res = await CourseService.updateChapterStatus(id, status)
      console.log(res)
      if (res[0] > 0) {
        response.success(ctx, res, '章节状态更新成功!')
      }
      // ctx.body = res
    } catch (error: any) {
      throw new UpdateChapterException(error, error.msg)
    }
  }

  @post('/saveOrUpdateLesson')
  async saveOrUpdateLesson(ctx: Context) {
    console.log(ctx.request.body)
    let lessonInfo = ctx.request.body

    try {
      const res: any = await CourseService.updateLesson(lessonInfo)
      // console.log(res)
      if ((res as any).id) {
        response.success(ctx, res, '课时新增成功!')
      } else if (res === true) {
        let data = {
          data: true
        }
        response.success(ctx, data, '课时更新成功！')
      } else {
        //这种情况处理的是课时不存在的情况
        throw new UpdateLessonException(
          '',
          '课时新增更新失败,更新的课时不存在！'
        )
      }
    } catch (error: any) {
      throw new UpdateChapterException(error, error.msg)
    }
  }

  //删除课时接口
  @del('/lesson')
  async deleteLesson(ctx: Context) {
    const _id = ctx.request.query.id

    const id = Number(_id)
    console.log(id)
    const res: any = await CourseService.findLessonById(id)
    console.log(res)
    if (res === -1) {
      response.failResponse(ctx, '课时不存在,无法删除！')
      return
    }
    const row: any = await CourseService.deleteLesson(id)
    if (row > 0) {
      response.success(ctx, { count: row }, '课时删除成功！')
    } else {
      response.failResponse(ctx, '课时删除失败!')
    }
  }

  //删除章节接口(章节下不存在课时情况下才能删除)
  @del('/chapter')
  async deleteChapter(ctx: Context) {
    const _id = ctx.request.query.id

    const id = Number(_id)
    console.log(id)
    const res: any = await CourseService.findLessonById(id)
    console.log(res)
    if (res === -1) {
      response.failResponse(ctx, '章节下存在课时,请先删除！')
      return
    }
    const row: any = await CourseService.deleteLesson(id)
    if (row > 0) {
      response.success(ctx, { count: row }, '章节删除成功！')
    } else {
      response.failResponse(ctx, '章节删除失败!')
    }
  }
}

export default new CourseController()
